#include "core/main.h"

FrameGrid::FrameGrid(const Frame &frame, int gridSize)
{
    // First find max x and y in the frame
    int maxX = 0;
    int maxY = 0;
    for (auto it = frame.sprites.begin(); it != frame.sprites.end(); ++it) {
        // SpriteLocation loc = *it;
        if (it->coord.x > maxX) maxX = it->coord.x;
        if (it->coord.y > maxY) maxY = it->coord.y;
    }

    _width = 1 + maxX / gridSize;
    _height = 1 + maxY / gridSize;

    data = new short[_width * _height];
    UINT *layer = new UINT[_width * _height];
    for (int i = 0; i < _width * _height; i++) {
        data[i] = -1;
        layer[i] = 0;
    }

    // Now populate data
    for (auto it = frame.sprites.begin(); it != frame.sprites.end(); ++it) {
        // const SpriteLocation &loc = *it;
        // cout << "Looking at SpriteLocation; x = " << loc.coord.x << " y = " << loc.coord.y << endl;
        // cout << "spriteLayer = " << loc.spriteLayer << endl;
        int xi = it->coord.x / gridSize;
        int yi = it->coord.y / gridSize;
        int idx = yi * _width + xi;

        // cout << "xi = " << xi << " yi = " << yi << endl;
        // cout << "existing spriteLayer is " << layer[idx] << endl;

        if (it->spriteLayer > layer[idx] || data[idx] == -1) {
            data[idx] = it->spriteID;
        }
    }

    delete[] layer;
}

int FrameGrid::getId(int x, int y) const
{
    if (x < 0 || x >= _width || y < 0 || y >= _height) {
        return -1;
    }
    return data[y * _width + x];
}

Neighborhood FrameGrid::getNeighborhood(int x, int y, int size) const
{
    return getNeighborhood(x, y, size, size);
}

Neighborhood FrameGrid::getNeighborhood(int x, int y, int width, int height) const
{
    Neighborhood neigh(width, height);
    for (int dy = 0; dy < height; dy++) {
        for (int dx = 0; dx < width; dx++) {
            neigh._data.push_back(getId(x + dx, y + dy));
        }
    }
    return neigh;
}